package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Article;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Author: wenjingyuan
 * @Date: 2023/03/28/11:01
 * @Description:获取文章的详情
 */
@WebServlet("/artdetail")
public class ArtDetailServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Article article=new Article();
        String msg="未知错误！";
        //1.取前端参数并校验
        String aidStr=req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)){
            //2.在数据库拿到详情
            Connection connection= DBUtils.getConnection();
            String sql="select * from article where aid=?";
            PreparedStatement statement=connection.prepareStatement(sql);
            statement.setInt(1,Integer.valueOf(aidStr));
            ResultSet resultSet=statement.executeQuery();
            if(resultSet.next()){
                article.setAid(resultSet.getInt("aid"));
                article.setTitle(resultSet.getString("title"));
                String ctime=resultSet.getString("createtime");
                article.setCreatetime(ctime.substring(0,ctime.lastIndexOf(".")));
                article.setContext(resultSet.getString("context"));
                article.setReadcount(resultSet.getInt("readcount"));

            }
            msg="成功";
            DBUtils.close(resultSet,statement,connection);
        }else{
            msg="参数错误！";
        }
        //3.后端返回给前端
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(
                200,article,msg
        )));
    }
}
